package mysql

import (
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

var (
	DB *gorm.DB
)

var LoggerFunc = DefaultLogger

func DefaultLogger() logger.Writer {
	return log.New(os.Stdout, "\r\n", log.LstdFlags)
}

func GetDB(dsn string) *gorm.DB {
	dbLogger := logger.New(
		LoggerFunc(),
		logger.Config{
			SlowThreshold: 200 * time.Millisecond,
			LogLevel:      logger.Info,
			Colorful:      true,
		})
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: dbLogger,
	})
	if err != nil {
		log.Fatalf("connect mysql failed: %v", err)
	}
	sqlDB, err := db.DB()
	if err != nil {
		log.Fatalf("mysql connect pool failed: %v", err)
	}
	sqlDB.SetMaxOpenConns(20)
	sqlDB.SetMaxIdleConns(10)

	DB = db
	log.Println("mysql connect success")
	return db
}
